<?php
namespace Admin\Controller;

use Think\Controller;

class OrderController extends RightController
{
    // 加载初始化内容页,并检索
    public function index()
    {
        //判断分页时搜索条件
        if (I("get.p")) {
            $where = session("QG_SEARCH_WHERE_orders");
            $params = session("QG_SEARCH_PARAMS_orders");
            $this->assign("params", session("QG_SEARCH_PARAMS_orders"));
            $where = empty($where) ? "1" : $where;
            $pageSize = session("QG_SEARCH_SIZE_orders");
        } else {
            //清除session存储
            session("QG_SEARCH_WHERE_orders", null);
            session("QG_SEARCH_PARAMS_orders", null);
            session("QG_SEARCH_SIZE_orders", null);
            $pageSize = I("post.pageSize");
            $params = I("post.");

            $where = "1";
        }

        // POST数据提交，重新组合检索条件
        if (IS_POST) {
            unset($_GET["p"]);
            $where = $this->searchCondition();
        }

        // 获取登录权限
        $account = $this->getAccount();


        // 分页输入
        if(empty($pageSize)){
            $pageSize = 10;
        }

        // 总条数
        $count = M('orders')
            ->alias("t")
            ->join(" LEFT JOIN member m ON m.id = t.memberId")
            ->join(" LEFT JOIN region r ON r.id = t.regionId")
            ->where($where)
            ->count();
        $page = new \Admin\Model\Page($count, $pageSize);
        $show = $page->show();

        // 进行分页数据查询
        $list = M('orders')
            ->alias("t")
            ->join(" LEFT JOIN member m ON m.id = t.memberId")
            ->join(" LEFT JOIN region r ON r.id = t.regionId")
            ->field("t.*,r.name_path as namePath,m.account as useraccount,m.nickname as username")
            ->where($where)
            ->order('t.id DESC')
            ->limit($page->firstRow . ',' . $page->listRows)->select();

        // 统计
        $sum = M('orders')
            ->alias("t")
            ->join(" LEFT JOIN member m ON m.id = t.memberId")
            ->join(" LEFT JOIN region r ON r.id = t.regionId")
            ->field("sum(t.total) as totalSum")
            ->where($where)
            ->order('t.id DESC')
            ->find();

        // 渲染查询条件到session
        $lists = array(
            "page" => getDropdownList("pageSize" , "" ,false),
            "orderStatus" => getDropdownList("orderStatus"),
            "orderType" => getDropdownList("orderType"),
//            "companyList" => $this->getBranchcompanyList()
        );
        $this->regionId($params['regionid'], $lists, $params);
        session("QG_SEARCH_WHERE_orders", $where);
        session("QG_SEARCH_PARAMS_orders", $params);
        session("QG_SEARCH_SIZE_orders", $pageSize);

        // 输出数据
        $this->assign("params", $params);
        $this->assign('list', $list);
        $this->assign('sum', $sum);
        $this->assign('lists', $lists);
        $this->assign('page', $show);
        $this->display();
    }

    // 搜索条件
    public function searchCondition()
    {
        $where = "1";

        // 如果是管理
        if ($this->isAdmin() && I('post.companyid')) {
            $where .= " AND a.companyid = '" . I('post.companyid') . "'";
        }

        // 会员手机
        if (I('post.sourceAccount')) {
            // 精确
            if (I('post.sourceAccountCondition') == 1) {
                $where .= " AND m.account='" . I("post.sourceAccount") . "'";
            } else {
                $where .= " AND m.account LIKE '%" . I("post.sourceAccount") . "%'";
            }
        }

        // 单号
        if (I('post.sn')) {
            // 精确
            if (I('post.snCondition') == 1) {
                $where .= " AND t.sn='" . I("post.sn") . "'";
            } else {
                $where .= " AND t.sn LIKE '%" . I("post.sn") . "%'";
            }
        }

        // 会员订单
        $where .= " AND t.orderType='1'";

        // 支付类型
        if (I('post.paytype')) {
            $where .= " AND t.payType='" . I("post.paytype") . "'";
        }

        // 上级代理
        if (I('post.toagenAccount')) {
            // 精确
            if (I('post.toagenAccountCondition') == 1) {
                $where .= " AND a.account = '" . I("post.toagenAccount") . "'";
            } else {
                $where .= " AND a.account LIKE '%" . I("post.toagenAccount") . "%'";
            }
        }

        // 状态
        if (I('post.status')) {
            $where .= " AND t.status='" . I("post.status") . "'";
        }

        // 总金额
        if (I('post.totalStart') || I('post.totalEnd')) {
            // 开始
            if(I('post.totalStart')){
                $where .= " AND t.total>='" . I("post.totalStart") . "'";
            }
            // 结束
            if(I('post.totalEnd')){
                $where .= " AND t.total<='" . I("post.totalEnd") . "'";
            }
        }


        // 创建时间
        if (I('post.createtimeStart') || I('post.createtimeEnd')) {
            // 起始日期
            if(I('post.createtimeStart')){
                $where .= " AND t.createTime>='" . I("post.createtimeStart") . "'";
            }
            // 结束日期
            if(I('post.createtimeEnd')){
                $where .= " AND t.createTime<='" . I("post.createtimeEnd") . " 23:59:59'";
            }
        }

        // 更新时间
        if (I('post.updatetimeStart') || I('post.updatetimeEnd')) {
            // 起始日期
            if(I('post.updatetimeStart')){
                $where .= " AND t.updateTime>='" . I("post.updatetimeStart") . "'";
            }
            // 结束日期
            if(I('post.updatetimeEnd')){
                $where .= " AND t.updateTime<='" . I("post.updatetimeEnd") . " 23:59:59'";
            }
        }

        // 地区ID
        if (I('post.regionid')) {
            $idPath = getIdPath(I('post.regionid'));
            $where .= " AND r.id_path LIKE '" . $idPath . "%'";
        }

        // 名字
        if (I('post.name')) {
            // 精确
            if (I('post.nameCondition') == 1) {
                $where .= " AND t.name='" . I("post.name") . "'";
            } else {
                $where .= " AND t.name LIKE '%" . I("post.name") . "%'";
            }
        }

        // 联系电话
        if (I('post.phone')) {
            // 精确
            if (I('post.phoneCondition') == 1) {
                $where .= " AND t.phone='" . I("post.phone") . "'";
            } else {
                $where .= " AND t.phone LIKE '%" . I("post.phone") . "%'";
            }
        }

        // 详细地址
        if (I('post.address')) {
            // 精确
            if (I('post.addressCondition') == 1) {
                $where .= " AND t.address='" . I("post.address") . "'";
            } else {
                $where .= " AND t.address LIKE '%" . I("post.address") . "%'";
            }
        }

        // 物流单号
        if (I('post.logistics')) {
            // 精确
            if (I('post.logisticsCondition') == 1) {
                $where .= " AND t.logistics='" . I("post.logistics") . "'";
            } else {
                $where .= " AND t.logistics LIKE '%" . I("post.logistics") . "%'";
            }
        }

        // 物流公司
        if (I('post.logisticscom')) {
            // 精确
            if (I('post.logisticscomCondition') == 1) {
                $where .= " AND t.logisticsCom='" . I("post.logisticscom") . "'";
            } else {
                $where .= " AND t.logisticsCom LIKE '%" . I("post.logisticscom") . "%'";
            }
        }
        // 支付类型
        if (I('post.belongagen')) {

            if (I('post.logisticscomCondition') == 1) {
                $where .= " AND a.account='" . I("post.belongagen") . "'";
            } else {
                $where .= " AND a.account LIKE  '%" . I("post.belongagen") . "%'";
            }

        }

        return $where;
    }

    // 详情
    public function info(){
        $id = I("id");
        $list = M("orderdetails")->where(array('orderId'=>$id))->select();
        foreach ($list as $k=>$v){
            $id = $v['id'];
            $spec_id = $v['spec_id'];
            if($spec_id != -1){
                $list[$k] =   M("orderdetails")
                    ->alias("o")
                    ->join(" LEFT JOIN product p ON p.id = o.productId")
                    ->where(array("o.id" => $id))
                    ->field("o.*,p.*")
                    ->find();
            }else{
                // 订单详情
                $list[$k] = M("orderDetails")
                    ->alias("o")
                    ->join(" LEFT JOIN product p ON p.id = o.productId")
                    ->where(array("o.id" => $id))
                    ->field("o.*,p.*")
                    ->find();
            }
        }
        $this->assign("list" ,$list);
        $this->display();
    }

    // 收货信息详情
    public function receipt(){
        $id = I("id");
        // 订单详情
        $data = M('orders')
            ->alias("t")
            ->join(" LEFT JOIN region r ON r.id = t.regionId")
            ->field("t.name,t.phone,t.address,t.logisticscom,t.logistics,t.status,r.name_path as namePath")
            ->where(array("t.id" => $id))
            ->find();

        $this->assign("data" ,$data);
        $this->display();
    }

    // 物流信息
    public function logistics(){
        $id = I("id");
        // 订单详情
        $data = M('orders')
            ->alias("t")
            ->field("t.logisticsCom,t.logistics")
            ->where(array("t.id" => $id))
            ->find();

        $this->assign("data" ,$data);
        $this->display();
    }

    public function change_logistics()
    {
        if(IS_POST){
            $id = I("id");
            $data['logistics'] = I('logistics');
            $data['logisticsCom'] = trim(I('logisticscom'));
            $data['updateTime'] = date("Y-m-d H:i:s");

            $res = M("orders")->where(array("id"=>$id))->save($data);
            if(false !== $res){
                $this->ajaxSuccess("物流信息修改成功！");
            }else{
                $this->ajaxError('修改失败！');
            }
        }

        $id = I("id");

        // 订单详情
        $data = M('orders')
            ->where(array("id" => $id))
            ->find();

        $logistics = getLogisticsList();
        $lists = array(
            "logistics" => $logistics
        );

        $this->assign("data" ,$data);
        $this->assign("lists" ,$lists);
        $this->display();
    }

    // 编辑收货信息
    public function receiptedit()
    {
        if (IS_POST) {
            $return = array();
            // ID
            $id = I("post.id");
            // 没有ID
            if(empty($id)){
                $this->ajaxError("错误！");
            }
            // 更新数据
            $data = array();
            // 姓名
            $data['name'] = I('post.name');
            // 手机
            $data['phone'] = I('post.phone');
            // 地区
            $data['regionId'] = I('post.regionid');
            // 详细地址
            $data['address'] = I('post.address');
            // 更新数据
            $result = M('orders')
                ->where(array("id" => $id))
                ->save($data);
            if ($result !== false) {
                $this->ajaxSuccess("更新成功！");
            } else {
                $this->ajaxError("更新失败！");
            }
        } else {
            // ID
            $id = intval(I("get.id"));
            // 判断是否存在
            $data = M('orders')
                ->alias("t")
                ->field("t.*")
                ->where(array("t.id" => $id))
                ->find();
            // 判断是否存在
            if (empty($data)) {
                $this->error("数据不存在");
            }
            $this->regionId($data['regionid'], $lists, $data);
            $this->assign('lists', $lists);
            $this->assign("data", $data);
            $this->display();
        }
    }
    // 删除
    public function delete()
    {
        if (IS_POST) {
            // ID
            $id = intval(I("post.id"));
            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }
            //删除数据
            $result = M('orders')->where(array("id" => $id))->delete();
            // 如果删除成功
            if ($result) {
                $this->ajaxSuccess("删除成功！");
            } else {
                $this->ajaxError("删除失败！");
            }
        }
    }

    //通过审核
    public function confirm()
    {
        if (IS_AJAX) {
            // ID
            $id = intval(I("post.id"));
            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }
            // flag
            $data['status'] = "9";
            // 更新时间
            $data['updateTime'] = now_datetime();
            // 更新数据
            $result = M('orders')->where(array("id" => $id))->save($data);
            // 如果成功
            if ($result) {
                $this->ajaxSuccess("审核成功！");
            } else {
                $this->ajaxError("审核失败！");
            }
        }
    }

    //驳回审核
    public function reject()
    {
        if (IS_AJAX) {
            // ID
            $id = intval(I("post.id"));
            // 没有ID
            if (empty($id)) {
                $this->ajaxError("错误！");
            }
            // flag
            $data['status'] = "7";
            // 更新时间
            $data['updateTime'] = now_datetime();
            // 更新数据
            $result = M('orders')->where(array("id" => $id))->save($data);
            // 如果成功
            if ($result) {
                $this->ajaxSuccess("驳回成功！");
            } else {
                $this->ajaxError("驳回 失败！");
            }
        }
    }

    // 发货
    public function send(){

        // 如果是post提交
        if(IS_POST){
            $id = I("post.id");
            $logisticsCom = I("post.logisticsCom");
            $logistics = I("post.logistics");
            if(strlen($logistics)<5){
                $this->ajaxError("单号不能小于5个字符");
            }

            // 如果订单有流转记录
            $msg = send($id,$logisticsCom,$logistics);

            // 如果有错误
            if(!empty($msg)){
                $this->ajaxError($msg);
            }else{
                $this->ajaxSuccess("发货成功");
            }
        }else{
            $id = I("id");

            // 订单详情
            $data = M('orders')
                ->where(array("id" => $id))
                ->find();

            $logistics = getLogisticsList();
            $lists = array(
                "logistics" => $logistics
            );

            $this->assign("data" ,$data);
            $this->assign("lists" ,$lists);
            $this->display();
        }
    }
}